<?php

namespace app\common\model\mysql;

use app\common\business\DataAuth;
use think\facade\Log;
use think\Model;

class SysDept extends Model
{
    /**
     * 自动生成写入时间
     * @var bool
     */
    protected $autoWriteTimestamp = true;

    /**
     * 新增前
     * @param $model
     * @return mixed|void
     */
    protected static function onBeforeInsert($model){
        $userData = (new DataAuth())->getUserDetails();
        $model->create_by = $userData['userName'];
    }

    /**
     * 更新前
     * @param $model
     * @return mixed|void
     */
    protected static function onBeforeUpdate($model)
    {
        $userData = (new DataAuth())->getUserDetails();
        $model->update_by = $userData['userName'];
    }

    /**
     * 查询部门列表
     * @param $field
     * @return SysDept[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNormalDept($where,$field){
        $order = [
            "dept_id" =>"asc",
            "order_num"=>"asc",
        ];
        $result = $this->where($where)->field($field)->order($order)->select();
        return $result;
    }

    /**
     * 查询单条数据部门
     * @param $where
     * @param $field
     * @return SysDept|array|mixed|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getFindNormalDept($where,$field){
        $result = $this->where($where)->field($field)->find();
        return $result;
    }

    /**
     * 根据部门名称获取部门数据
     * @param $Deptname
     * @return SysDept|array|false|mixed|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getDeptByDeptname($Deptname,$parentId,$dept_id){
        if(empty($Deptname)){
            return false;
        }
        $where = [
            "dept_name" =>$Deptname,
            "parent_id"=>$parentId,
        ];
        if($dept_id){
            $result = $this->where("dept_id", "<>", $dept_id)->where($where)->find();
        }else{
            $result = $this->where($where)->find();
        }
        return $result;
    }

    /**
     * 获取无限极分类列表
     * @param int $parentId 父级ID，默认为0表示顶级分类
     * @return array
     */
    public function getDeptTree($parentId = 0,$where = [])
    {
        // 初始化查询条件
        $map = [
            ['parent_id', '=', $parentId],
            ['del_flag', '=', 0],
        ];
        // 如果提供了额外的where条件，则合并它们
        if (!empty($where)) {
            $map[] = ['dept_id', 'in', $where];
        }
        $categories = $this->where($map)->order('order_num', 'asc')->field("dept_id as id,dept_name as label")->select()->toArray();
        // 递归构建树形结构
        $tree = [];
        foreach ($categories as &$category) {
            // 递归获取子分类
            $category['children'] = $this->getDeptTree($category['id'],$where);
            // 将当前分类添加到树中
            $tree[] = &$category;
        }
        // 注意：由于使用了引用，需要取消引用以避免潜在的问题
        unset($category);
        return $tree;
    }

    /**
     * 获取指定分类及其所有子分类的ID
     * @param $categoryId
     * @param $ids
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAllCategoryIds($parentId, &$ids = [])
    {
        // 首先将当前分类ID添加到结果数组中
        $ids[] = $parentId;
        // 查询当前分类的所有直接子分类
        $map = ['parent_id' => $parentId, 'del_flag' => 0];
        $children = $this->where($map)->order('order_num', 'asc')->field("dept_id as id")->select();
        // 遍历子分类，并对每个子分类递归调用此函数
        foreach ($children as $child) {
            self::getAllCategoryIds($child['id'], $ids);
        }
    }

    /**
     * 获取指定分类及其所有子分类的ID列表
     * @param $parentId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAllChildrenIds($parentId)
    {
        $ids = [];
        self::getAllCategoryIds($parentId, $ids);
        return $ids;
    }

    //获取部门下parent_id数组集合
    public function deptParentIdData(){
        $where = [
            "del_flag" => 0,
        ];
        $result = $this->where($where)->column('parent_id');
        return $result;
    }

    public function deptIdsData($parentIds){
        if(empty($parentIds)){
            return false;
        }
        $where = [
            ['parent_id','in',$parentIds]
        ];
        $result = $this->where($where)->column('dept_id');
        return $result;
    }
}
